<script lang="ts">
import 'plyr/dist/plyr.css'
</script>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import Plyr from 'plyr'

export type VPlyrCaptions = {
  src: string
  srclang: string
  default?: boolean
}
export type VPlyrFormat = '4by3' | '16by9' | 'square'
export interface VPlyrProps {
  source: string
  title: string
  poster: string
  captions?: VPlyrCaptions[]
  reversed?: boolean
  embed?: boolean
  ratio?: VPlyrFormat
  options?: Plyr.Options
}

const props = withDefaults(defineProps<VPlyrProps>(), {
  ratio: '16by9',
  options: () => ({}),
  captions: () => [],
})

const player = ref<Plyr>()
const videoElement = ref<HTMLElement>()

onMounted(() => {
  if (videoElement.value) {
    player.value = new Plyr(videoElement.value, props.options)
  }
})

onBeforeUnmount(() => {
  if (player.value) {
    player.value.destroy()
    player.value = undefined
  }
})
</script>

<template>
  <div
    class="video-player-container"
    :class="[ratio && 'is-' + ratio, reversed && 'reversed-play']"
  >
    <!-- video element -->
    <iframe
      v-if="embed"
      :src="`${source}`"
      :title="props.title"
      allowfullscreen
      allowtransparency
      allow="autoplay"
    ></iframe>

    <video
      v-else
      ref="videoElement"
      controls
      crossorigin="anonymous"
      playsinline
      :data-poster="poster"
    >
      <source :src="source" type="video/mp4" />
      <track
        v-for="(caption, key) in props.captions"
        :key="key"
        :default="caption.default"
        kind="captions"
        :srclang="caption.srclang"
        :src="caption.src"
      />
    </video>
  </div>
</template>
